/**
 * Created by KaiBo on 2016-12-7.
 */


$.fn.schedule = function (options) {
    /*
     * 用于记录日期，显示的时候，根据dateObj中的日期的年月显示
     */
    var dateObj = (function () {
        var _date = new Date();    // 默认为当前系统时间
        return {
            getDate: function () {
                return _date;
            },
            setDate: function (date) {
                _date = date;
            }
        };
    })();
    var defaults = {
        // 在html标签中存放的属性名称；
        $calendar: $("#calendar"),
        month: [],
        getDriverUrl: '',
        // 父元素默认为window
        container: window

    };
    // 不管有没有传入参数，先合并再说；
    var params = $.extend({}, defaults, options || {});


    //初始化
    init();
    // 设置calendar div中的html部分
    renderHtml();
    // 表格中显示日期
    // 绑定事件
    bindEvent();

    /**
     * 初始化
     */
    function init() {
        setMonth();
    }

    /**
     * 设置行程
     */
    function setMonth() {
        var temp = {};
        for (var i = 1; i <= 31; i++) {
            temp[i] = false;
        }
        var _dateStr = getDateStr(dateObj.getDate());
        var date = _dateStr.substr(0, 4) + "-" + _dateStr.substr(4, 2);
        $.post(params.getDriverUrl, {
            DRIVER: params.driverId,
            DATE: date
        }, function (data) {
            var jsonData = eval(data);
            for (var i in jsonData) {
                var day = jsonData[i].DATE.substr(8, 2);
                day = parseInt(day);
                temp[day] = jsonData[i].TYPE;
            }
            params.month = temp;
            showCalendarData();
        });
    }

    /**
     * 构造日程详情
     */
    function createDay(type, sTime, remark) {
        var html = '';
        html += '<div class="row schedule-list">';
        html += '    <div class="col-xs-12">';
        html += '        <div class="schedule-type '+type+'">';

        switch (type) {
            case "busyDay":
                html += '            请假';
                break;
            case "meetDay":
                html += '            接机';
                html += '    <span class="text-success  schedule-time">';
                html += getTime(sTime);
                html += '    </span>';
                break;
            case "charteredDay":
                html += '            包车/一日游';
                html += '    <span class="text-success schedule-time">';
                html += getTime(sTime);
                html += '    </span>';
                break;
            default:
        }

        html += '        </div>';
        html += '    </div>';

        html += '    <div class="col-xs-12 schedule-info">';
        html += remark;
        html += '    </div>';

        html += ' </div>';

        return html;
    }

    /**
     * 分钟转换成事件
     */
    function getTime(data) {
        var hour = parseInt(data / 60);
        var minute = parseInt(data % 60);
        minute = minute > 0 ? minute : "00";
        minute = minute< 10 ? "0"+minute : minute;
        var date = hour + ":" + minute;
        return date;
    }

    /**
     * 渲染html结构
     */
    function renderHtml() {
        var $calendar = params.$calendar;

        // 设置标题盒子中的html
        var html = '<div class="calendar-title-box">';
        html += '     <span class="prev-month glyphicon glyphicon-menu-left" id="prevMonth"></span>';
        html += '     <span class="calendar-title" id="calendarTitle"></span>';
        html += '     <span id="nextMonth" class="next-month glyphicon glyphicon-menu-right"></span>';
        html += '</div>';

        // 设置表格区的html结构
        var _headHtml = "<tr>" +
            "<th>日</th>" +
            "<th>一</th>" +
            "<th>二</th>" +
            "<th>三</th>" +
            "<th>四</th>" +
            "<th>五</th>" +
            "<th>六</th>" +
            "</tr>";
        var _bodyHtml = "";

        // 一个月最多31天，所以一个月最多占6行表格
        for (var i = 0; i < 6; i++) {
            _bodyHtml += "<tr>" +
                "<td></td>" +
                "<td></td>" +
                "<td></td>" +
                "<td></td>" +
                "<td></td>" +
                "<td></td>" +
                "<td></td>" +
                "</tr>";
        }
        html += "<div class='calendar-body-box'>";
        html += "<table id='calendarTable' class='calendar-table'>";
        html += _headHtml + _bodyHtml;
        html += "</table>";
        html += "</div>";
        // 添加到calendar div中
        $calendar.html(html);
    }

    /**
     * 表格中显示数据，并设置类名
     */
    function showCalendarData() {
        var _year = dateObj.getDate().getFullYear();
        var _month = dateObj.getDate().getMonth() + 1;
        var _dateStr = getDateStr(dateObj.getDate());
        // 设置顶部标题栏中的 年、月信息
        var $calendarTitle = $("#calendarTitle");
        var titleStr = _dateStr.substr(0, 4) + "年" + _dateStr.substr(4, 2) + "月" + _dateStr.substr(6, 2) + "日";
        $calendarTitle.html(titleStr);

        // 设置表格中的日期数据
        var _firstDay = new Date(_year, _month - 1, 1);  // 当前月第一天
        $("#calendarTable td").each(function (index) {
            var $this = $(this);
            var _thisDay = new Date(_year, _month - 1, index + 1 - _firstDay.getDay());
            var _thisDayStr = getDateStr(_thisDay);

            $this.html(_thisDay.getDate());
            $this.attr("data", _thisDayStr);

            if (_thisDayStr.substr(0, 6) == getDateStr(_firstDay).substr(0, 6)) {    // 当前天
                $this.removeClass().addClass("currentMonth"); // 当前月
                var month = params.month[parseInt(_thisDay.getDate())];
                if ( month ) {
                    if(month == '-1'){
                        //请假
                        $this.removeClass().addClass("busyDay");
                    }else if(month == '0'){
                        //接机，送机
                        $this.removeClass().addClass("meetDay");
                    }else if(month == '1' || month == '2'){
                        //包车
                        $this.removeClass().addClass("charteredDay");
                    }
                }
                if (_thisDayStr == getDateStr(new Date())) {
                    var type = $this.attr('class');
                    var date = _thisDayStr.substr(0, 4) + "-" + _thisDayStr.substr(4, 2) + "-" + _thisDayStr.substr(6, 2);
                    $.post(params.getDriverUrl, {
                        DRIVER: params.driverId,
                        DATE: date
                    }, function (data) {
                        var json = eval(data);
                        var html = '';
                        for (var i in json) {
                            html += createDay(type, json[i].STIME, json[i].REMARK);
                        }
                        $("#scheduleList").html(html);
                    });
                }
            } else {
                $this.removeClass().addClass("otherMonth");        // 其他月
            }
        });
    }

    /**
     * 绑定上个月下个月事件
     */
    function bindEvent() {
        $("#prevMonth").off("click").click(toPrevMonth);
        $("#nextMonth").off("click").click(toNextMonth);

        $("#calendar").off("click","td").on("click", "td", function () {
            var $this = $(this);
            var type = $this.attr('class');
            if ($this.hasClass("otherMonth")) {
                return;
            }

            var date = $this.attr("data");
            date = date && 1 ? date : null;
            if(date){
                date = date.substr(0, 4) + "-" + date.substr(4, 2) + "-" + date.substr(6, 2);
            }
            $.post(params.getDriverUrl, {
                DRIVER: params.driverId,
                DATE: date
            }, function (data) {
                var json = eval(data);
                var html = '';
                for (var i in json) {
                    html += createDay(type, json[i].STIME, json[i].REMARK);
                }
                $("#scheduleList").html(html);
            });

            var $calendarTitle = $("#calendarTitle");
            var _dateStr = $this.attr("data");
            var titleStr = _dateStr.substr(0, 4) + "年" + _dateStr.substr(4, 2) + "月" + _dateStr.substr(6, 2) + "日";
            $calendarTitle.html(titleStr);

            $("#calendar td").removeClass("selectedDay");
            $(this).addClass("selectedDay");
        });
        $(".edit-schedule").off("click").click(function () {
            $(".edit-container").slideDown().siblings("div").slideUp();
            $("body").css("background", "white");
        });
        $(".btn-cancel").off("click").click(function () {
            $(".schedule-container").slideDown().siblings("div").slideUp();
            $(".edit-schedule-container").slideDown();
            $(".top").slideDown();
            $("body").css("background", "#f0f0f0");

        })
    }

    /**
     * 点击上个月图标触发
     */
    function toPrevMonth() {
        var date = dateObj.getDate();
        dateObj.setDate(new Date(date.getFullYear(), date.getMonth() - 1, 1));
        $("#scheduleList").empty();
        setMonth();
    }

    /**
     * 点击下个月图标触发
     */
    function toNextMonth() {
        var date = dateObj.getDate();
        dateObj.setDate(new Date(date.getFullYear(), date.getMonth() + 1, 1));
        $("#scheduleList").empty();
        setMonth();
    }

    /**
     * 日期转化为字符串， 4位年+2位月+2位日
     */
    function getDateStr(date) {
        var _year = date.getFullYear();
        var _month = date.getMonth() + 1;    // 月从0开始计数
        var _d = date.getDate();
        _month = (_month > 9) ? ("" + _month) : ("0" + _month);
        _d = (_d > 9) ? ("" + _d) : ("0" + _d);
        return _year + _month + _d;
    }
};
